import { InfoCircleOutlined } from '@ant-design/icons';
import { useDebounceFn } from 'ahooks';
import { Flex, Spin } from 'antd';
import React, { useEffect, useState } from 'react';

import knowService from '@/api/services/knowService';
import { Tooltip, Button, Search, Content } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import NotData from '@/components/NotData';
import PagesHeader from '@/components/pages-header';
import Tables from '@/components/tables/tables';
import TipDesc from '@/components/tipDesc/tipDesc';
import { useParams } from '@/router/hooks';
import { DuplicateCollection, KnowSimilarityCollection } from '@/types/know/know';

import '../../styles/know-gov.scss';
import FileCompareModal from '../../sub-pages/document/components/FileCompareModal';

const DocumentSimilarity: React.FC = () => {
  const [search, setSearch] = useState('');
  const [data, setData] = useState<KnowSimilarityCollection[]>([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [currentCollection, setCurrentCollection] = useState<KnowSimilarityCollection | null>(null);
  const [fileCompareModalVisible, setFileCompareModalVisible] = useState(false);

  const { appId = '' } = useParams() as { appId: string };
  // 监听分页和搜索框变化，获取数据
  useEffect(() => {
    run();
  }, [page, pageSize, search]);

  // 使用防抖函数，延迟获取数据
  const { run } = useDebounceFn(
    () => {
      getDatas();
    },
    {
      wait: 500,
    },
  );

  const getDatas = async () => {
    try {
      setLoading(true);
      const res = await knowService.getSimilarity({
        page,
        page_size: pageSize,
        searchText: search,
        appId,
        offset: (page - 1) * pageSize,
      });
      setData(res.list);
      setTotal(res.total);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 搜索功能（mock）
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value);
    setPage(1);
    setPageSize(10);
  };

  // 分页
  const handlePageChange = (page: number, pageSize?: number) => {
    setPage(page);
    setPageSize(pageSize || 10);
  };

  const dcColumns = [
    {
      title: '文件名',
      dataIndex: 'fileName',
      key: 'fileName',
    },
    {
      title: '文档所属',
      width: '10%',
      dataIndex: 'datasetName',
      key: 'datasetName',
      render: (datasetName: string) => {
        return <div>{datasetName}</div>;
      },
    },
    {
      title: '状态',
      width: '10%',
      dataIndex: 'status',
      key: 'status',
      render: (_: KnowSimilarityCollection, record: KnowSimilarityCollection) => {
        const dealLength = record?.duplicateList?.filter((item) => item.status !== 0)?.length || 0;
        const base = record.status === 0 ? 0 : 1;
        const total = record?.duplicateList?.length + 1 || 0;
        return <div>{`${dealLength + base}/${total}`}</div>;
      },
    },
    {
      title: '相似文档数',
      width: '10%',
      dataIndex: 'duplicateList',
      key: 'duplicateList',
      render: (duplicateList: []) => {
        return (
          <div>
            {duplicateList?.length || 0}{' '}
            <Tooltip
              className="cursor-pointer"
              rootClassName="know-gov-document-tooltip"
              title={() => {
                return (
                  <div
                    style={{
                      maxHeight: '400px',
                      whiteSpace: 'pre-wrap',
                      overflow: 'auto',
                    }}
                  >
                    <div className="text-base">相似文档数：({duplicateList?.length || 0})</div>
                    <div className="grid grid-cols-4 gap-2">
                      <div className="col-span-2">文档</div>
                      <div>相似度</div>
                      <div>状态</div>
                      {duplicateList?.map((item: DuplicateCollection, index: number) => (
                        <React.Fragment key={index}>
                          <div className="col-span-2 flex min-w-0 flex-col">
                            <div className="">{item.name}</div>
                            <div className="truncate text-nowrap text-xs text-[#A5A9BB]">
                              知识库：{item.datasetName}
                            </div>
                          </div>
                          <div>{Number((item.similarity * 100).toFixed(2))}%</div>
                          <div>{item.status === 0 ? '未处理' : '已处理'}</div>
                        </React.Fragment>
                      ))}
                    </div>
                  </div>
                );
              }}
            >
              <InfoCircleOutlined />
            </Tooltip>
          </div>
        );
      },
    },
    {
      title: '操作',
      width: '10%',
      key: 'operation',
      render: (_: KnowSimilarityCollection, record: KnowSimilarityCollection) => (
        <Button size="small" className="ml-auto" type="text" onClick={() => onHandle(record)}>
          <span className="text-primary">
            {' '}
            <SvgIcon icon="message-ic19" size="20" className="mr-1" />
            处理
          </span>
        </Button>
      ),
    },
  ];

  const onHandle = (item: KnowSimilarityCollection) => {
    setCurrentCollection(item);
    setFileCompareModalVisible(true);
  };
  const updateCurrentCollection = (collection: KnowSimilarityCollection) => {
    if (
      collection.isDeleted ||
      (collection?.duplicateList && collection?.duplicateList.length <= 0)
    ) {
      setCurrentCollection(null);
      setFileCompareModalVisible(false);
    } else {
      setCurrentCollection(collection);
    }
  };
  const onCompareModalCancel = () => {
    setFileCompareModalVisible(false);
    setCurrentCollection(null);
  };

  const completed = () => {
    setFileCompareModalVisible(false);
    setCurrentCollection(null);
  };

  return (
    <div className="flex h-full flex-col bg-white">
      <PagesHeader>
        文档重复
        <TipDesc
          title="计算知识库中文档之间的相似度，识别高度重复的内容，并进行可视化呈现，方便后续管理和优化。"
          className="!my-0"
        />
      </PagesHeader>
      <div className="flex flex-1 flex-col rounded-default px-5">
        <div className="my-4 flex items-center justify-between">
          <div>
            <Search value={search} onChange={handleSearch} placeholder="搜索" />
          </div>
        </div>
        <div className="flex flex-1 flex-col">
          {loading ? (
            <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
              <Spin size="large" />
            </Flex>
          ) : (
            <Content>
              {data.length > 0 ? (
                <Tables
                  rowKey="_id"
                  columns={dcColumns}
                  dataSource={data}
                  pagination={false}
                  className="border border-gray-100"
                  paginationProps={{
                    total,
                    current: page,
                    pageSize,
                    onChange: handlePageChange,
                  }}
                />
              ) : (
                <NotData />
              )}
            </Content>
          )}
        </div>
      </div>
      <FileCompareModal
        open={fileCompareModalVisible}
        collection={(currentCollection as KnowSimilarityCollection)!}
        setCollection={updateCurrentCollection}
        onCancel={onCompareModalCancel}
        completed={completed}
      />
    </div>
  );
};

export default DocumentSimilarity;
